import re
import uuid
from functools import wraps

from hashlib import md5

from flask import session, redirect, g


def login_auth(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        user = session.get('user')
        if user:
            g.user = user
            return func(*args, **kwargs)
        return redirect('/app/login/')

    return wrapper


def pwd_md5(password):
    result = md5(password.encode()).hexdigest()
    return result


def photo_update_name(string):
    if re.match(r'.+\..+', string):
        string = string[::-1]
        end = ''
        name = str(uuid.uuid1())
        for char in string:
            if char == '.':
                end += '.'
                break
            end += char
        name += end[::-1]
        return name
    return None
